<?php
namespace Modules\Home\Controllers;

use Common\Models\UserModel;

use Modules\Home\Services\UserService;
use Modules\Home\Services\UserInfoService;
use Modules\Home\Services\UserAchievementService;
use Modules\Home\Services\UserWalletService;
use Modules\Home\Services\UserWalletGoodsLogService;
use Modules\Home\Services\UserWalletActivationCodeLogService;

class UserRegisterController extends ControllerBase {
  public function initialize() {
    parent::initialize();

    $this -> _checkLogin();
    $this -> view -> setLayout('index');
  }

  public function indexAction() {
    $this -> tag -> prependTitle('新会员注册');

    $user = $this -> session -> get('user');

    $findUserNoedSide = UserModel::find('node_user_id = ' . $user['user_id'] . ' AND node_side in(1, 2)');
    if($findUserNoedSide -> count() >= 2) {
      $this -> view -> nodeSideMessage = '左右区已满';
      $this -> view -> nodeSide = null;
    } else {
      $this -> view -> nodeSideMessage = $user['real_name'];
      $nodeSide = [
        1 => '左区',
        2 => '右区',
      ];
      foreach($findUserNoedSide as $userNoedSide) {
        unset($nodeSide[$userNoedSide -> node_side]);
      }

      $this -> view -> nodeSide = $nodeSide;
    }
    
    $this -> view -> currentUser = $user;
  }

  public function createAction() {
    $this -> response  -> setContentType('application/json', 'UTF-8');
    $resultJson = [
      'code' => -1,
      'msg' => '未知错误'
    ];

    // 验证
    $validation = (new \Modules\Home\Validations\UserValidation()) -> create($this -> request -> getPost(), ['user'=>$this->session->get('user'), 'USER_REGISTER_FIRST_POINT_REWARD' => $this -> getParameter('USER_REGISTER_FIRST_POINT_REWARD')]);
    if($validation['code'] != 0) {
      $resultJson['code'] = $validation['code'];
      $resultJson['msg'] = $validation['message'];
      return $this -> response -> setJsonContent($resultJson);
    }
    $currentTime = time();

    $this -> db -> begin();
    try {
      $createUserService = (new UserService()) -> create($validation['post']['user']);
      if($createUserService['code'] != 0) {
        throw new \Exception($createUserService['message'] . __LINE__);
      }

      $validation['post']['user_info']['user_id'] = $createUserService['user'] -> user_id;

      $USER_REGISTER_ACTIVATION_CODE = $this -> getParameter('USER_REGISTER_ACTIVATION_CODE');
      $USER_WALLET_GOODS_AGENT_REWARD = $this -> getParameter('USER_WALLET_GOODS_AGENT_REWARD');

      $createUserWalletActivationCodeLog = (new \Modules\Home\Services\UserWalletActivationCodeLogService()) -> create([
        'user_id' => $validation['service_user_wallet'] -> user_id,
        'from_user_id' => $createUserService['user'] -> user_id,
        'type' => 51,
        'active' => 0,
        'create_time' => $currentTime,
        'amount' => $USER_REGISTER_ACTIVATION_CODE['value'],
        'amount_new' => $validation['service_user_wallet'] -> activation_code - $USER_REGISTER_ACTIVATION_CODE['value'],
        'amount_old' => $validation['service_user_wallet'] -> activation_code,
        'remark' => '店代理注册 - 注册用户 - 消耗激活码'
      ]);
      if($createUserWalletActivationCodeLog['code'] != 0) {
        throw new \Exception($createUserWalletActivationCodeLog['message'] . __LINE__);
      }

      $createUserWalletGoodsLogService = (new \Modules\Home\Services\UserWalletGoodsLogService()) -> create([
        'user_id' => $validation['service_user_wallet'] -> user_id,
        'from_user_id' => $createUserService['user'] -> user_id,
        'type' => 86,
        'active' => 1,
        'is_draw' => 0,
        'draw_time' => 0,
        'create_time' => $currentTime,
        'amount' => $USER_WALLET_GOODS_AGENT_REWARD['value'],
        'amount_new' => 0,
        'amount_old' => 0,
        'service_charge' => 0,
        'remark' => '店代理注册 - 注册用户 - 店代理奖'
      ]);
      if($createUserWalletGoodsLogService['code'] != 0) {
        throw new \Exception($createUserWalletGoodsLogService['message'] . __LINE__);
      }

      $validation['service_user_wallet'] -> activation_code -= $USER_REGISTER_ACTIVATION_CODE['value'];
      if(!$validation['service_user_wallet'] -> update()) {
        throw new \Exception('注册失败' . __LINE__);
      }

      $createUserWallet = (new \Modules\Home\Services\UserWalletService()) -> getOne($createUserService['user'] -> user_id);
      if($createUserWallet['code'] != 0) {
        throw new \Exception('注册失败' . __LINE__);
      }

      $USER_REGISTER_COUPON = $this -> getParameter('USER_REGISTER_COUPON');

      $UserWalletCouponLogModel = new \Common\Models\UserWalletCouponLogModel([
        'user_id' => $createUserService['user'] -> user_id,
        'from_user_id' => $validation['service_user_wallet'] -> user_id,
        'type' => 31,
        'active' => 1,
        'create_time' => $currentTime,
        'amount' => $USER_REGISTER_COUPON['value'],
        'amount_new' => $createUserWallet['user_wallet'] -> coupon + $USER_REGISTER_COUPON['value'],
        'amount_old' => $createUserWallet['user_wallet'] -> coupon,
        'remark' => '店代理注册 - 注册用户 - 购物券转入'
      ]);
      if(!$UserWalletCouponLogModel -> create()) {
        throw new \Exception('注册失败,' . __LINE__);
      }

      $createUserWallet['user_wallet'] -> coupon += $USER_REGISTER_COUPON['value'];
      if(!$createUserWallet['user_wallet'] -> update()) {
        throw new \Exception('注册失败,' . __LINE__);
      }
      

      $createUserInfoService = (new UserInfoService()) -> create($validation['post']['user_info']);
      if($createUserInfoService['code'] != 0) {
        throw new \Exception($createUserInfoService['message'] . __LINE__);
      }

      $this -> db -> commit();
    } catch(\Exception $e) {
      $this -> db -> rollback();

      $resultJson['code'] = -1;
      //$resultJson['msg'] = 'Line:' . $e -> getLine() . ', Message: ' . $e -> getMessage();
      $resultJson['msg'] = $e -> getMessage();
      return $this -> response -> setJsonContent($resultJson);
    }

    $resultJson['code'] = 0;
    $resultJson['msg'] = '注册成功';
    $resultJson['url'] = '/user/register';
    return $this -> response -> setJsonContent($resultJson);
  }
}
?>